package com.dong.c03_channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * <h1></h1>
 *Scattering : 分散: 将数据写入到buffer时, 可以采用buffer数组依次写入
 * Gathering : 分散,将数据读出时, 可以采用buffer数组,依次读
 * @author : dzj
 * @create: 2020-03-18 00:30
 */
public class P8_ScatteringAndGatheringTest {
    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);
        serverSocketChannel.socket().bind(inetSocketAddress);

        //创建buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0]= ByteBuffer.allocate(5);
        byteBuffers[1]= ByteBuffer.allocate(3);
        //等待客户端连接
        SocketChannel socketChannel = serverSocketChannel.accept();
        int byteRead = 0;
        int msgLength =8;
        long byteWrite=0;

        while (true) {
            while(byteRead<msgLength) {

                long readLen = socketChannel.read(byteBuffers);
                byteRead+=readLen;
                System.out.println("byteRead="+byteRead);

            }
            Arrays.asList(byteBuffers).stream().map(buffer-> "position="+buffer.position()+", limit="+buffer.limit()).forEach(System.out::println);
            System.out.println("*****************************");


            Arrays.asList(byteBuffers).forEach(b->b.flip());
            //将数据读出, 并显示到客户端

            while(byteWrite<msgLength) {
                long l = socketChannel.write(byteBuffers);
                byteWrite+=l;
                System.out.println("byteWrite: "+byteWrite+"currentWrite: "+l);
                Thread.sleep(1000);
            }
            Arrays.asList(byteBuffers).forEach(b->b.clear());
            System.out.println("byteRead:"+byteRead+", byteWrite: "+byteWrite+", msgLen: "+msgLength);
            System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        }

    }
}
